<?php
/**
 * Created by PhpStorm.
 * User: 12133
 * Date: 2024/3/21
 * Time: 9:56
 */

// 网站URL和要监测的内容选择器
$url = "http://example.com";
$contentSelector = "p#content"; // 假设我们要监测的是id为"content"的段落元素

// 初始爬取并保存哈希值
function initialCrawlAndSaveHash($url, $contentSelector) {
    $content = file_get_contents($url);
    $contentToCheck = extractContent($content, $contentSelector);
    $hashValue = calculateHash($contentToCheck);
    file_put_contents("content_hash.txt", $hashValue);
    echo "初始哈希值已保存。\n";
}

// 提取指定选择器的内容
function extractContent($html, $selector) {
    $dom = new DOMDocument();
    @$dom->loadHTML($html); // 使用@来抑制可能的警告
    $xpath = new DOMXPath($dom);
    $elements = $xpath->query($selector);
    if ($elements->length > 0) {
        return $dom->saveHTML($elements->item(0));
    }
    return "";
}

// 计算内容的哈希值
function calculateHash($content) {
    return hash('sha256', $content);
}

// 定期监测并比较哈希值
function monitorChanges($url, $contentSelector) {
    while (true) {
        $content = file_get_contents($url);
        $contentToCheck = extractContent($content, $contentSelector);
        $currentHash = calculateHash($contentToCheck);

        $previousHash = file_get_contents("content_hash.txt");

        if ($currentHash !== $previousHash) {
            echo "内容已被篡改！\n";
            // 在这里可以添加报警逻辑，如发送邮件等
        } else {
            echo "内容未变。\n";
        }

        // 等待一段时间后再次检查
        sleep(3600); // 每小时检查一次
    }
}

// 初始爬取并保存哈希值
initialCrawlAndSaveHash($url, $contentSelector);

// 开始监测
monitorChanges($url, $contentSelector);